package com.lakeworks.framework.security.filter;

import com.lakeworks.common.core.domain.model.LoginUser;
import com.lakeworks.framework.web.service.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

import static com.lakeworks.common.utils.SecurityUtils.getAuthentication;
import static com.lakeworks.common.utils.StringUtils.isNotNull;
import static com.lakeworks.common.utils.StringUtils.isNull;

/**
 * @Author: Auxps
 * @Date: 2023/3/1
 * Description:
 */
@Component
public class WechatAuthenticationTokenFilter extends OncePerRequestFilter {

    @Value("${server.servlet.context-path}")
    private String contextPath;

    private static final String CHANNEL_PATTERN = "/channel/**";

    private static final AntPathMatcher ANT_PATH_MATCHER = new AntPathMatcher();

    @Autowired
    private TokenService tokenService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        if (ANT_PATH_MATCHER.match(contextPath.concat(CHANNEL_PATTERN), request.getRequestURI())) {
            chain.doFilter(request, response);
            return;
        }
        LoginUser loginUser = tokenService.getLoginUser(request);
        if (isNotNull(loginUser) && isNull(getAuthentication()) && !loginUser.getPermissions().isEmpty()) {
            PreAuthenticatedAuthenticationToken authenticationToken = new PreAuthenticatedAuthenticationToken(loginUser, null, loginUser.getAuthorities());
            authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        }
        chain.doFilter(request, response);
    }

}
